package com.zhuchaooasystem.presenter.home;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zhuchaooasystem.api.HttpApi;
import com.zhuchaooasystem.api.HttpFactory;
import com.zhuchaooasystem.api.RxResultHelper;
import com.zhuchaooasystem.api.download.DownloadProgressHandler;
import com.zhuchaooasystem.api.download.ProgressHelper;
import com.zhuchaooasystem.base.BasePresenter;
import com.zhuchaooasystem.base.SchedulersCompat;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.ClientEntity;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.ToastUtil;
import com.zhuchaooasystem.widget.ConfirmDialog;
import com.zhuchaooasystem.widget.DownloadDialog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscription;
import rx.functions.Action1;


/**
 * Created by zhangyajiang on 2016/12/22.
 */

public class HomePresenter extends BasePresenter<HomeContract.View> implements HomeContract.Presenter {
    private String apkFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + Key.PATH_LOCAL_APK;
    private String apkName = "zhuchaooa.apk";
    private ProgressBar progressBar;

    private TextView txtProgress;

    public HomePresenter(Activity activity, HomeContract.View view) {
        super(activity, view);
    }

    @Override
    public void checkVersion() {
        //----
        final Map<String, String> map = new HashMap<>();
        map.put("remark", "Android");
        map.put("Version", AppUtils.getAppVersionName(mActivity));
        //----
        Subscription subscription = HttpFactory.getHttpApi().updateInterfaceByOA(map)
                .compose(SchedulersCompat.applyIoSchedulers())
                .compose(RxResultHelper.handleResult()).subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (null != o) {
                            final ClientEntity entity = (ClientEntity) o;
                            if (null != entity.getList() && entity.getList().isIsRealease()) {
                                showConfirmDialog(entity.getList().getDownloadUrl());
                            }

                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
        addSubscrebe(subscription);
    }

    private void showConfirmDialog(final String url) {
        ConfirmDialog dialogConfirm = new ConfirmDialog(mActivity);
        dialogConfirm.show();
        dialogConfirm.setTextTitle("版本更新");
        dialogConfirm.setTextContent("检测到有新版本，是否要下载更新？");
        dialogConfirm.setOnViewClickListener(new ConfirmDialog.OnViewClickListener() {

            @Override
            public void onClickOk(ConfirmDialog dialog) {
                dialog.dismiss();
                if (!TextUtils.isEmpty(url)) {
                    DownloadDialog downloadDialog = showDownloadDialog();
                    downloadApk(url, downloadDialog);
                } else {
                    ToastUtil.showShort(mActivity, "更新地址出错");
                }
            }

            @Override
            public void onClickCancel(ConfirmDialog dialog) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 显示软件下载进度对话框
     *
     * @return
     */
    private DownloadDialog showDownloadDialog() {
        DownloadDialog dialog = new DownloadDialog(mActivity);
        dialog.show();
        dialog.setTextTitle("下载进度");
        progressBar = dialog.getProgressBar();
        txtProgress = dialog.getTxt_progress();
        return dialog;
    }


    private void downloadApk(String url, final DownloadDialog downloadDialog) {

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://www.zhuchao.com");
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
        HttpApi retrofit = retrofitBuilder
                .client(builder.build())
                .build().create(HttpApi.class);

        ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
            @Override
            protected void onProgress(long bytesRead, long contentLength, boolean done) {
                progressBar.setMax((int) (contentLength / 1024));
                progressBar.setProgress((int) (bytesRead / 1024));
                txtProgress.setText((int) (bytesRead * 100 / contentLength) + "%");
                if (done) {
                    downloadDialog.dismiss();
                }
            }
        });

        retrofit2.Call<ResponseBody> call = retrofit.retrofitDownload();
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                InputStream is = null;
                FileOutputStream fos = null;
                BufferedInputStream bis = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(apkFilePath, apkName);
                    fos = new FileOutputStream(file);
                    bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        fos.flush();
                    }
                    ToastUtil.showShort(mActivity, "下载成功");
                    installApp(file.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fos.close();
                        bis.close();
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                ToastUtil.showShort(mActivity, "下载失败");
            }
        });

    }

    /**
     * 安装apk
     *
     * @param appFile
     */
    private void installApp(String appFile) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            File file = new File(appFile);
            intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
            mActivity.startActivity(intent);
        } catch (Exception e) {
        }
    }


}